<template>
  <div class="submitorder">
    <div class="submitordertitle">
      <van-nav-bar
        title="提交订单"
        :left-text="'返回'"
        @click-left="back"
        fixed
      ></van-nav-bar>
    </div>

    <div class="dizhi">
      <div class="van-addressadd">
        <div class="select-address" @click="ischeak">
          <div>选择收货地址</div>
          <van-icon name="arrow" />
        </div>
        <div class="info">
          <div class="infoname">{{ selectaddress.name }}</div>
          <div class="infophone">{{ selectaddress.tel }}</div>
        </div>
        <div class="address">
          {{ selectaddress.city }}{{ selectaddress.county
          }}{{ selectaddress.addressDetail }}
        </div>
      </div>

      <van-popup v-model="show">
        <van-address-edit
          show-postal
          show-set-default
          :area-columns-placeholder="['请选择', '请选择', '请选择']"
          :area-list="areaList"
          :address-info="addressInfo"
          @save="newAddress"
        />
      </van-popup>

      <van-popup v-model="setshow">
        <van-address-edit
          show-postal
          show-delete
          show-set-default
          :area-columns-placeholder="['请选择', '请选择', '请选择']"
          :area-list="areaList"
          :address-info="addressInfo"
          @save="setAddress"
          @delete="deleteAddress"
        />
      </van-popup>

      <van-popup v-model="cheak" position="bottom">
        <van-address-list
          v-model="chosenAddressId"
          :list="list"
          default-tag-text="默认"
          @add="onadd"
          @edit="onedit"
          @select="onselect"
        />
      </van-popup>
    </div>
    <div class="lists-item">
      <h3>订单信息</h3>
      <van-empty description="你没有选择商品哦，到处逛逛吧" v-if="isshow">
        <van-button round type="danger" class="bottom-button" @click="goshop"
          >去订单看看</van-button
        >
      </van-empty>
      <van-swipe-cell v-for="(value, index) in resultdata" :key="index">
        <van-cell-group>
          <div class="cell-box">
            <div class="cell-img">
              <img class="auto-img" :src="value.small_img" alt />
            </div>
            <div class="cell-info">
              <div class="info-top">
                {{ value.name }}
                <span>{{ value.rule }}</span>
              </div>
              <div class="info-center">{{ value.enname }}</div>
              <div class="info-bottom">
                <div class="price">￥{{ value.price }}</div>
                <div>x {{ value.count }}</div>
              </div>
            </div>
          </div>
        </van-cell-group>
      </van-swipe-cell>
    </div>
    <div class="sum">
      <div class="num">共计 {{ resultdata.length }} 件商品</div>
      <div class="sums">合计￥{{ sum }}</div>
    </div>
    <div class="btn">
      <van-button type="primary" @click="uporder">提交订单</van-button>
    </div>
  </div>
</template>

<script>
import { Dialog } from 'vant'
import { areaList } from '@vant/area-data'
import { getToken } from '@/utils/storage'
import {
  findAddressAPI,
  commitShopcartAPI,
  editAddressAPI,
  deleteAddressAPI,
  addAddressAPI,
  payAPI
} from '@/api/user'
import '../assets/less/submitorder.less'

export default {
  data () {
    return {
      // 是否显示无订单框
      isshow: false,
      show: false,
      cheak: false,
      setshow: false,
      // 商品号
      sids: '',
      // 商品列表
      resultdata: {},
      // 订单总价格
      sum: 0,
      areaList,
      // 地址数据初始值
      addressInfo: {
        id: '',
        name: '',
        tel: '',
        province: '',
        city: '',
        county: '',
        addressDetail: '',
        areaCode: '',
        postalCode: '',
        isDefault: false
      },
      chosenAddressId: '1',
      list: [],
      // 选择的地址
      selectaddress: {},
      // 地址
      address: '',
      // 判断是从哪里进来的数据
      ischeaks: false
    }
  },
  created () {
    // 获取传过来的参数
    if (!getToken()) return this.$router.push({ name: 'Login' })
    this.sids = this.$route.query.obj
    this.ischeaks = this.$route.query.ischeaks
    this.each()
    this.loading()
  },
  beforeRouteLeave (to, from, next) {
    next(true)
    if (this.ischeaks) {
      this.remove(this.sids)
    }
  },
  methods: {
    // 返回上一级
    back () {
      this.$router.go(-1)
    },
    // 去购物袋
    goshop () {
      this.$router.push({ name: 'Dingdan' })
    },
    ischeak () {
      // findAddress
      this.cheak = !this.cheak
    },
    // 加载选中的商品
    loading () {
      const tokenString = getToken()
      if (this.sids) {
        console.log('this.sids', this.sids)
        commitShopcartAPI({
          appkey: this.$store.state.appkey,
          tokenString,
          sids: this.sids
        }).then(res => {
          console.log(res)
          if (res.code === 50000) {
            this.resultdata = res.result
            this.resultdata.forEach(v => {
              this.sum += v.count * v.price
            })
          }
          if (res.code === 50001) {
            this.resultdata = {}
            this.isshow = true
          } else {
            this.isshow = false
          }
        })
      }
    },
    // 增加新的地址
    newAddress (address) {
      const content = Object.assign({}, address)
      delete content.id
      delete content.country
      content.isDefault = Number(content.isDefault)
      content.appkey = this.$store.state.appkey
      content.tokenString = getToken()
      addAddressAPI(content).then(res => {
        this.each()
        this.show = false
      })
    },
    // 删除地址
    deleteAddress (address) {
      if (!address.aid) {
        return
      }
      const tokenString = getToken()
      deleteAddressAPI({
        appkey: this.$store.state.appkey,
        tokenString,
        aid: address.aid
      }).then(res => {
        this.addressInfo = {
          id: '',
          name: '',
          tel: '',
          province: '',
          city: '',
          county: '',
          addressDetail: '',
          areaCode: '',
          postalCode: '',
          isDefault: false
        }
        this.each()
        this.show = false
        this.setshow = false
      })
    },
    // 查询地址
    async each () {
      // 在订单页面获取token，如果没有则去登录页面
      const tokenString = getToken()
      const res = await findAddressAPI({
        appkey: this.$store.state.appkey,
        tokenString
      })
      if (res) {
        res.result.forEach(v => {
          if (v.isDefault) {
            this.selectaddress = v
            this.address = v.city + v.county + v.addressDetail
          }
        })
        this.list = res.result
      }
    },
    // 编辑地址
    onedit (item) {
      this.setshow = !this.setshow
      this.addressInfo = item
    },
    // 设置地址
    setAddress (address) {
      const content = Object.assign({}, address)
      const tokenString = getToken()
      delete content.id
      delete content.country
      content.isDefault = Number(content.isDefault)
      content.appkey = this.$store.state.appkey
      content.tokenString = tokenString
      content.aid = this.addressInfo.aid
      editAddressAPI(content).then(res => {
        this.each() // 重新调用查询地址接口来渲染
      })
    },
    // 选择地址
    onselect (item) {
      this.selectaddress = item
      this.cheak = false
    },
    // 新增地址
    onadd () {
      this.show = !this.show
      //  初始化
      this.addressInfo = {
        id: '',
        name: '',
        tel: '',
        province: '',
        city: '',
        county: '',
        addressDetail: '',
        areaCode: '',
        postalCode: '',
        isDefault: false
      }
    },
    // 提交订单
    uporder () {
      if (!this.selectaddress.aid) {
        Dialog.alert({
          message: '你没有选择地址哦'
        }).then(() => {})
        return
      }
      const tokenString = getToken()
      payAPI({
        appkey: this.$store.state.appkey,
        tokenString,
        sids: this.sids,
        phone: this.selectaddress.tel,
        address: this.address,
        receiver: this.selectaddress.name
      }).then(res => {
        this.sids = []
        this.sids = JSON.stringify(this.sids)
        if (res.code === 60001) return
        if (res.code === 60000) {
          this.$toast(res.msg)
          return this.$router.push({ name: 'Dingdan' })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
